package com.zn.opit.videoframe.utils;

import com.zn.opit.videoframe.exception.VideoFrameException;
import com.zn.opit.videoframe.exception.VideoFrameExceptionTypes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
public class FileUtil {

    // 默认文件名
    private static final String defaultFilename = "file";

    public static FileItem createFileItem(InputStream inputStream) {
        final String filename = defaultFilename + "." +  MediaType.IMAGE_JPEG.getSubtype();
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(filename, MediaType.MULTIPART_FORM_DATA_VALUE, true, filename);
        try(OutputStream os = item.getOutputStream()) {
            IOUtils.copy(inputStream, os);
        } catch (IOException e) {
            log.error("create fileItem stream copy occurred exception", e);
            throw new VideoFrameException(VideoFrameExceptionTypes.FILE_CREATE_FAILED);
        }
        return item;
    }
}
